﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.Xml;
using System.Net;
using Infragistics.Win.UltraWinGrid;

namespace DMSClient.Distributors
{
    public partial class OrderInvoiceDetails : Form
    {
        private DMSServices.DMSServicesClient client;
        private DataTable dt;

        private DataTable dtOrderItems;
        private DataTable dtInvoiceItems;
        DataTable dtOrderInvoiceDetails;
        private string ambient;
        //--
        string idDistributor = "";
        string dtInvoiceStart = "";
        string dtInvoiceEnd = "";
        string cdInvoice = "";
        string modoConsulta = "";
        string fileNameToExport = "";
        static bool fileExported = false;
       

        public OrderInvoiceDetails() { InitializeComponent(); }

        public OrderInvoiceDetails(string idDistributor, string dtInvoiceStart, string dtInvoiceEnd, string cdInvoice, string ambient, string [] dataHead, string modoConsulta_REV)
        {            
            InitializeComponent();
            
              this.idDistributor=idDistributor;
              this.dtInvoiceStart=dtInvoiceStart;
              this.dtInvoiceEnd = dtInvoiceEnd;
              this.cdInvoice = cdInvoice;
              this.ambient = ambient;
              this.modoConsulta = modoConsulta_REV;
            
            //orders
              txtOCodErp.Text = dataHead[0].ToString(); //Codigo de la orden //cod ERP    = cdOrder
              txtORegion.Text = dataHead[1].ToString();//Codifo de la region//region      = cdRegion
              txtODiscountTotal.Text = dataHead[2].ToString();//Descuento total aplicado a la orden//total descuento = vlDiscountTotal
              txtOTotalOrder.Text = dataHead[3].ToString();//Valor total de la orden//valor total     = vlTotalOrder
              txtOdate.Text = Convert.ToDateTime(dataHead[4].ToString().Trim()).ToShortDateString();//Fecha de la orden//fecha Orden   =     dtOrder       
              txtOEstatus.Text = dataHead[5].ToString();//Estado de la Orden//estado orden  =      cdStatusOrder 
              txtOUnitsOrder.Text = dataHead[6].ToString();//numero total de lineas en la oren =  vlTotalUnit
             //Invoice
              txtICodDocument.Text = dataHead[7].ToString();//cod Documento   = cdInvoice
              txtIDescription.Text = dataHead[8].ToString();//Descripcion     = dsDisplayText            
              txtItotalProduct.Text = dataHead[9].ToString();//total productos = nrTotalQuantity
              txtITotalInvoice.Text = dataHead[10].ToString(); //valor total     = vlTotalInvoice
              txtIDate.Text = Convert.ToDateTime(dataHead[11].ToString().Trim()).ToShortDateString();//fecha factura   = dtInvoice 
              txtIStatus.Text = dataHead[12].ToString();//estado factura   = dtInvoice 
            //ORDERS vs INVOICES
              txtOVI_cdOrder.Text = txtOCodErp.Text; txtOVI_cdInvoice.Text = txtICodDocument.Text;
              txtOVI_vltotalOrder.Text = txtOTotalOrder.Text; txtOVI_vlTotalInvoice.Text = txtITotalInvoice.Text;
              txtOVI_productosOrder.Text = ""; txtOVI_productosInvoice.Text = txtItotalProduct.Text;
              txtOVI_fechaOrder.Text = txtOdate.Text; txtOVI_fechaInvoice.Text = txtIDate.Text;
            //Alertas y mensaje
              if (!txtOVI_vltotalOrder.Text.Trim().Equals(txtOVI_vlTotalInvoice.Text.Trim())) 
              {
                  lblCompareEncabezados.ForeColor = Color.Red;
              }
            


              
           
            //this.ambient = Properties.Settings.Default.CurrentEnv;
            this.Text = this.ambient + " - Order Items || Invoice Items - Report";

            WSHttpBinding Binding = new WSHttpBinding();
            Binding.MaxReceivedMessageSize = Int32.MaxValue;
            Binding.MaxBufferPoolSize = Int32.MaxValue;
            Binding.CloseTimeout = TimeSpan.MaxValue;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            Binding.Security.Mode = SecurityMode.None;

            EndpointAddress address = new EndpointAddress(Properties.Settings.Default.Server);
            client = new DMSServices.DMSServicesClient(Binding, address);

            activarControles(false);
            bgWorker_DetailsInvoice.RunWorkerAsync();
        }

        private void OrderInvoiceDetails_Load(object sender, EventArgs e)
        {                
        }

        private void cargarGrid_detailsInvoice()
        {

            WSHttpBinding binding = new WSHttpBinding();
            binding.CloseTimeout = new TimeSpan(0, 1, 0);
            binding.OpenTimeout = new TimeSpan(0, 1, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
            binding.SendTimeout = new TimeSpan(0, 1, 0);
            binding.Security.Mode = SecurityMode.None;
            binding.MaxReceivedMessageSize = Int32.MaxValue;
            binding.MaxBufferPoolSize = Int32.MaxValue;
            binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
            binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            binding.Security.Mode = SecurityMode.None;


            EndpointAddress address = new EndpointAddress(Properties.Settings.Default.Server);
            DMSServices.DMSServicesClient service = new DMSServices.DMSServicesClient(binding, address);
            DMSServices.DMSServicesClient serviceII = new DMSServices.DMSServicesClient(binding, address);

            string respuesta = null;
            //--DATOS Detalles
            try
            {
                service.Open();
                respuesta = service.getOItemsInvoiceByInvoiceReport(idDistributor, DateTime.Parse(dtInvoiceStart), DateTime.Parse(dtInvoiceEnd),cdInvoice, this.ambient);               
                service.Close();
                respuesta = Compression.Decompress(respuesta);

                //Creamos la tabla donde cargaremos los datos
                dtOrderItems = new DataTable("DT_ImportOrderItemInvoiceItem_ByInvoice");
                dtInvoiceItems = new DataTable("DT_ImportOrderItemInvoiceItem_ByInvoice");
               

                dtOrderItems.Columns.Add("cdOrder", typeof(string));
                dtOrderItems.Columns.Add("cdProduct", typeof(string));
               // dtOrderItems.Columns.Add("dsproduct", typeof(string));//Agregado 15-03-2011
                dtOrderItems.Columns.Add("nrSequenceOrder", typeof(Int32));
                dtOrderItems.Columns.Add("nrQuantityOrder", typeof(Int32));
                dtOrderItems.Columns.Add("vlDiscountSubtotal", typeof(float));
                dtOrderItems.Columns.Add("vlSubTotalOrder",typeof(float));
                dtOrderItems.Columns.Add("cdInvoice", typeof(string));
                dtOrderItems.Columns.Add("nrSequenceInvoice", typeof(Int32));
                dtOrderItems.Columns.Add("nrQuantityInvoice", typeof(Int32));
                dtOrderItems.Columns.Add("vlSubtotalInvoice", typeof(float));
                //--
                dtInvoiceItems.Columns.Add("cdOrder", typeof(string));
                dtInvoiceItems.Columns.Add("cdProduct", typeof(string));               
                dtInvoiceItems.Columns.Add("nrSequenceOrder", typeof(Int32));
                dtInvoiceItems.Columns.Add("nrQuantityOrder", typeof(Int32));
                dtInvoiceItems.Columns.Add("vlDiscountSubtotal", typeof(float));
                dtInvoiceItems.Columns.Add("vlSubTotalOrder", typeof(float));
                dtInvoiceItems.Columns.Add("cdInvoice", typeof(string));
                //dtInvoiceItems.Columns.Add("dsproduct", typeof(string));//Agregado 15-03-2011
                dtInvoiceItems.Columns.Add("nrSequenceInvoice", typeof(Int32));
                dtInvoiceItems.Columns.Add("nrQuantityInvoice", typeof(Int32));
                dtInvoiceItems.Columns.Add("vlSubtotalInvoice", typeof(float));
              
                DataSet dsOrderItems = new DataSet("dsOrderItems");
                dsOrderItems.Tables.Add(dtOrderItems);
                System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
                dsOrderItems.ReadXml(xmlSR, XmlReadMode.ReadSchema);
                xmlSR.Close();

                DataSet dsInvoiceItems = new DataSet("dsInvoiceItems");
                dsInvoiceItems.Tables.Add(dtInvoiceItems);
                System.IO.StringReader xmlSRII = new System.IO.StringReader(respuesta);
                dsInvoiceItems.ReadXml(xmlSRII, XmlReadMode.ReadSchema);
                xmlSRII.Close();               
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
            //--DATOS VISTA INTERFACE DETAILS
            respuesta = null;
            try
            {
                serviceII.Open();
                //modoConsulta:
                //"|1" para que el modo de consulta consulte por las fechas de INVOICES
                //"|2" para que el modo de consulta consulte por las fechas de ORDERS        
                //Acá no importa si es uno o dos por que igual consulta todos los detalles.
                respuesta = serviceII.getOItemsInvoiceReport(idDistributor + "|" + modoConsulta, DateTime.Parse(dtInvoiceStart), DateTime.Parse(dtInvoiceEnd), this.ambient);
                serviceII.Close();
                respuesta = Compression.Decompress(respuesta);

                dtOrderInvoiceDetails = new DataTable("DT_ImportOrderItemInvoiceItem");
                dtOrderInvoiceDetails.Columns.Add("cdOrder");
                dtOrderInvoiceDetails.Columns.Add("cdProduct");
                dtOrderInvoiceDetails.Columns.Add("nrSequenceOrder");
                dtOrderInvoiceDetails.Columns.Add("nrQuantity");
                dtOrderInvoiceDetails.Columns.Add("vlDiscountSubtotal");
                dtOrderInvoiceDetails.Columns.Add("vlSubTotalOrder");
                dtOrderInvoiceDetails.Columns.Add("cdInvoice");
                dtOrderInvoiceDetails.Columns.Add("nrSequenceInvoice");
                dtOrderInvoiceDetails.Columns.Add("nrQuantityInvoice");
                dtOrderInvoiceDetails.Columns.Add("vlSubtotalInvoice");

                DataSet dataSet = new DataSet("DS_ImportOrderItemInvoiceItem");
                dataSet.Tables.Add(dtOrderInvoiceDetails);
                System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
                dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
                xmlSR.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
                  
        }



        private void bgWorker_DetailsInvoice_DoWork(object sender, DoWorkEventArgs e)
        {
            cargarGrid_detailsInvoice();
        }

        private void bgWorker_DetailsInvoice_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!this.IsDisposed)
            {
                try {                                        
                    //Cargabndo los details Orders
                    ugDetailsOrder.DataSource = dtOrderItems;                    
                    dtOrderItems.Columns["cdInvoice"].ColumnMapping = MappingType.Hidden;
                    dtOrderItems.Columns["nrSequenceInvoice"].ColumnMapping = MappingType.Hidden;
                    dtOrderItems.Columns["nrQuantityInvoice"].ColumnMapping = MappingType.Hidden;
                    dtOrderItems.Columns["vlSubtotalInvoice"].ColumnMapping = MappingType.Hidden;
                    ugDetailsOrder.DataBind();
                    //Cargar datos para la vista de interfaz                   
                    ug_OrderItemsInvoiceItems_interfaceView.DataSource = dtOrderInvoiceDetails;
                    ug_OrderItemsInvoiceItems_interfaceView.DataBind();
                

                    //Así las oculataba antes pero con los cambios ya no funciona
                    //ugDetailsOrder.DisplayLayout.Bands[0].Columns["cdInvoice"].Hidden = false;
                    //ugDetailsOrder.DisplayLayout.Bands[0].Columns["nrSequenceInvoice"].Hidden = false;
                    //ugDetailsOrder.DisplayLayout.Bands[0].Columns["nrQuantityInvoice"].Hidden = false;
                    //ugDetailsOrder.DisplayLayout.Bands[0].Columns["vlSubtotalInvoice"].Hidden = false;


                    //Cargabndo los details Invoice
                    ugDetailsInvoice.DataSource = dtInvoiceItems;                    
                    dtInvoiceItems.Columns["cdOrder"].ColumnMapping = MappingType.Hidden;
                    //dtInvoiceItems.Columns["cdProduct"].ColumnMapping = MappingType.Hidden;
                    dtInvoiceItems.Columns["nrSequenceOrder"].ColumnMapping = MappingType.Hidden;
                    dtInvoiceItems.Columns["nrQuantityOrder"].ColumnMapping = MappingType.Hidden;
                    dtInvoiceItems.Columns["vlDiscountSubtotal"].ColumnMapping = MappingType.Hidden;
                    dtInvoiceItems.Columns["vlSubTotalOrder"].ColumnMapping = MappingType.Hidden;
                    ugDetailsInvoice.DataBind();
                    //Así las oculataba antes pero con los cambios ya no funciona
                    //ugDetailsOrder.DisplayLayout.Bands[0].Columns["cdOrder"].Hidden = false;
                    //ugDetailsOrder.DisplayLayout.Bands[0].Columns["cdProduct"].Hidden = false;
                    //ugDetailsOrder.DisplayLayout.Bands[0].Columns["nrSequenceOrder"].Hidden = false;
                    //ugDetailsOrder.DisplayLayout.Bands[0].Columns["nrQuantityOrder"].Hidden = false;
                    //ugDetailsOrder.DisplayLayout.Bands[0].Columns["vlDiscountSubtotal"].Hidden = false;
                    //ugDetailsOrder.DisplayLayout.Bands[0].Columns["vlSubTotalOrder"].Hidden = false;
                    //--Añadiendo la columna de SUMMARYS ORDER
                    //--------------------------------------------------------------------------------------------------------
                    //SUM:SubTotal de la orden
                    //--------------------------------------------------------------------------------------------------------
                    Infragistics.Win.UltraWinGrid.UltraGridBand band = this.ugDetailsOrder.DisplayLayout.Bands[0];            
                    Infragistics.Win.UltraWinGrid.SummarySettings summary = band.Summaries.Add(Infragistics.Win.UltraWinGrid.SummaryType.Sum, band.Columns["vlSubTotalOrder"]);
                    summary.SummaryPosition = Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn;
                    summary.DisplayFormat = "Total ={0:$##########0.#####0}";
                    summary.Key = "SUM_vlSubtotalOrders";
                    summary.Appearance.TextHAlign = Infragistics.Win.HAlign.Left;
                    summary.Appearance.ForeColor = Color.DarkBlue;
                    summary.Appearance.BackColor = Color.Gray;
                    band.Override.BorderStyleSummaryValue = Infragistics.Win.UIElementBorderStyle.Solid;
                    //Apariencia del pie de reporte
                    band.Override.SummaryFooterAppearance.BackColor = Color.White;
                    band.Override.SummaryFooterCaptionAppearance.BackColor = Color.White;
                    band.SummaryFooterCaption = "";
                    //--------------------------------------------------------------------------------------------------------
                    //SUM: total discount
                    //--------------------------------------------------------------------------------------------------------
                    band = this.ugDetailsOrder.DisplayLayout.Bands[0];
                    summary = band.Summaries.Add(Infragistics.Win.UltraWinGrid.SummaryType.Sum, band.Columns["vlDiscountSubtotal"]);
                    summary.SummaryPosition = Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn;
                    //summary.DisplayFormat = "Total Discount = {0}";
                    summary.DisplayFormat ="Total Discount = {0:$##########0.#####0}";
                    summary.Key = "SUM_vlDiscountSubtotal";
                    summary.Appearance.TextHAlign = Infragistics.Win.HAlign.Left;
                    summary.Appearance.ForeColor = Color.DarkBlue;
                    summary.Appearance.BackColor = Color.Gray;
                    band.Override.BorderStyleSummaryValue = Infragistics.Win.UIElementBorderStyle.Solid;
                    //Apariencia del pie de reporte
                    band.Override.SummaryFooterAppearance.BackColor = Color.White;
                    band.Override.SummaryFooterCaptionAppearance.BackColor = Color.White;
                    band.SummaryFooterCaption = "";
                    //--------------------------------------------------------------------------------------------------------
                    //SUM:SubTotal de productos en la orden
                    //--------------------------------------------------------------------------------------------------------
                    band = this.ugDetailsOrder.DisplayLayout.Bands[0];                    
                    summary = band.Summaries.Add(Infragistics.Win.UltraWinGrid.SummaryType.Sum, band.Columns["nrQuantityOrder"]);
                    summary.SummaryPosition = Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn;
                    summary.DisplayFormat = "Total Producs= {0}";           

                    summary.Key = "SUM_nrQuantityOrder";
                    summary.Appearance.TextHAlign = Infragistics.Win.HAlign.Left;
                    summary.Appearance.ForeColor = Color.DarkBlue;
                    summary.Appearance.BackColor = Color.Gray;
                    band.Override.BorderStyleSummaryValue = Infragistics.Win.UIElementBorderStyle.Solid;
                    //Apariencia del pie de reporte
                    band.Override.SummaryFooterAppearance.BackColor = Color.White;
                    band.Override.SummaryFooterCaptionAppearance.BackColor = Color.White;
                    band.SummaryFooterCaption = "";


                    
                    //--Añadiendo la columna de SUMMARYS INVOICE
                    //-----------------------------------------
                    //--------------------------------------------------------------------------------------------------------
                    //SUM:SubTotal Invoice
                    //--------------------------------------------------------------------------------------------------------
                    band = this.ugDetailsInvoice.DisplayLayout.Bands[0];
                    summary = band.Summaries.Add(Infragistics.Win.UltraWinGrid.SummaryType.Sum, band.Columns["vlSubtotalInvoice"]);
                    summary.SummaryPosition = Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn;
                    summary.DisplayFormat = "Total = {0:$##########0.#####0}";
                    summary.Key = "SUM_vlSubtotalInvoice";
                    summary.Appearance.TextHAlign = Infragistics.Win.HAlign.Left;
                    summary.Appearance.ForeColor = Color.DarkBlue;
                    summary.Appearance.BackColor = Color.Gray;
                    band.Override.BorderStyleSummaryValue = Infragistics.Win.UIElementBorderStyle.Solid;
                    //Apariencia del pie de reporte
                    band.Override.SummaryFooterAppearance.BackColor = Color.White;
                    band.Override.SummaryFooterCaptionAppearance.BackColor = Color.White;
                    band.SummaryFooterCaption = "";
                    //--------------------------------------------------------------------------------------------------------
                    //SUM:SubTotal de productos en Invoice
                    //--------------------------------------------------------------------------------------------------------
                    band = this.ugDetailsInvoice.DisplayLayout.Bands[0];
                    summary = band.Summaries.Add(Infragistics.Win.UltraWinGrid.SummaryType.Sum, band.Columns["nrQuantityInvoice"]);
                    summary.SummaryPosition = Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn;
                    summary.DisplayFormat = "Total Products = {0}";
                    summary.Key = "SUM_nrQuantityInvoice";
                    summary.Appearance.TextHAlign = Infragistics.Win.HAlign.Left;
                    summary.Appearance.ForeColor = Color.DarkBlue;
                    summary.Appearance.BackColor = Color.Gray;
                   
                    band.Override.BorderStyleSummaryValue = Infragistics.Win.UIElementBorderStyle.Solid;
                    //Apariencia del pie de reporte
                    band.Override.SummaryFooterAppearance.BackColor = Color.White;
                    band.Override.SummaryFooterCaptionAppearance.BackColor = Color.White;
                    band.SummaryFooterCaption = "";
                }
                catch (Exception ee) 
                {
                    throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ee.InnerException);
                }                  
                activarControles(true);
            }
            else if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activarControles(true);
                }
            }
           
        }


        //----------------------

               
        private void activarControles(bool value)
        {
            loader.Visible = !value;
            loader1.Visible = !value;
            ultraGroupBox1.Enabled = value;
            ultraGroupBox2.Enabled = value;
            ugDetailsInvoice.Enabled = value;
            ugDetailsOrder.Enabled = value;
        }

        private void OrderInvoiceDetails_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bgWorker_EXPORT.IsBusy)
            {
                bgWorker_EXPORT.CancelAsync();
            }

            if (bgWorker_DetailsInvoice.IsBusy)
            {
                bgWorker_DetailsInvoice.CancelAsync();
            }
        }     

        private void btnCerrarFRM_Click(object sender, EventArgs e)
        {
            if (bgWorker_EXPORT.IsBusy)
            {
                bgWorker_EXPORT.CancelAsync();
            }

            if (bgWorker_DetailsInvoice.IsBusy)
            {
                bgWorker_DetailsInvoice.CancelAsync();
            }
            this.Close();
        }

        private void ugDetailsOrder_SummaryValueChanged(object sender, Infragistics.Win.UltraWinGrid.SummaryValueChangedEventArgs e)
        {
            if (e.SummaryValue.Key == "SUM_vlSubtotalOrders")
            {                
                txtOVI_SUMtotalOrderItems.Text = e.SummaryValue.SummaryText.ToString().Split('$').GetValue(1).ToString();
                txtOVI_SUMtotalOrderItems.Text = txtOVI_SUMtotalOrderItems.Text.Replace(",", ".");
                if (float.Parse(txtOVI_SUMtotalOrderItems.Text.Trim()) != float.Parse(txtOTotalOrder.Text.Trim())) 
                {
                    txtOVI_SUMtotalOrderItems.BackColor = Color.Red;
                }
            }
            else if (e.SummaryValue.Key == "SUM_nrQuantityOrder") 
            {
                txtOVI_productosOrder.Text = e.SummaryValue.Value.ToString();
                txtOVI_SUMproductosOrderItems.Text = txtOVI_productosOrder.Text;
                //Para marcar la diferencia entre productos oreder e invoice
                if (!txtOVI_productosOrder.Text.Trim().Equals(txtOVI_productosInvoice.Text.Trim()))
                {
                    lblCompareProductos.ForeColor = Color.Red;
                }
            }
           
        }

        private void ugDetailsInvoice_SummaryValueChanged(object sender, Infragistics.Win.UltraWinGrid.SummaryValueChangedEventArgs e)
        {
            if (e.SummaryValue.Key == "SUM_vlSubtotalInvoice")
            {
                txtOVI_SUMTotalInvoiceItems.Text = e.SummaryValue.SummaryText.ToString().Split('$').GetValue(1).ToString();
                txtOVI_SUMTotalInvoiceItems.Text = txtOVI_SUMTotalInvoiceItems.Text.Replace(",", ".");                
                if (float.Parse(txtOVI_SUMTotalInvoiceItems.Text.Trim()) != float.Parse(txtITotalInvoice.Text.Trim()))
                {
                    txtOVI_SUMTotalInvoiceItems.BackColor = Color.Red;
                }
            }
            else if (e.SummaryValue.Key == "SUM_nrQuantityInvoice") 
            {                
                txtOVI_SUMProductosInvoiceItems.Text = e.SummaryValue.Value.ToString();
                if (float.Parse(txtOVI_SUMProductosInvoiceItems.Text.Trim()) != float.Parse(txtOVI_productosInvoice.Text.Trim()))
                {
                    txtOVI_SUMProductosInvoiceItems.BackColor = Color.Red;
                }
            }
        }

        private void ugDetailsOrder_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

        private void OrderInvoiceDetails_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)27)
            {
                this.Close();
            }
        }

        private void ugDetailsInvoice_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

        private void uBtnExporReport_Click(object sender, EventArgs e)
        {
            if (ug_OrderItemsInvoiceItems_interfaceView.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", "OrderItemsInvoicesItems Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }


            if (MessageBox.Show(this, "The data will be exported interface view. Continue?", "OrderItemsInvoicesItems Report", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
                dialogo.DefaultExt = "pdf";
                dialogo.Filter = ". pdf | (Pdf File)";
                if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    activarControles(false);
                    fileNameToExport = dialogo.FileName;
                    bgWorker_DetailsInvoice.CancelAsync();
                    bgWorker_EXPORT.RunWorkerAsync();
                }
            }
            else
            {
                return;
            }              
        }

        private void bgWorker_EXPORT_DoWork(object sender, DoWorkEventArgs e)
        {
            TXTExport d = new TXTExport(TXTExport_F);
            this.Invoke(d, new object[] { fileNameToExport });
        }

        private void bgWorker_EXPORT_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!this.IsDisposed)
            {
                activarControles(true);
                if (fileExported)
                {
                    fileExported = false;
                    System.Diagnostics.Process.Start(fileNameToExport);
                }
            }
            else if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activarControles(true);
                }
            }
        }

        //Exportar reporte a TXT
        //--------------------------------------------------------------------------------------
        //Delegado para poder acceder a controles en el DoWork
        delegate void TXTExport(string nombreYruta);

        /*Exporta a PDF*/
        private void TXTExport_F(string nombreYruta)
        {
            loader.Visible = true;
            try
            {
                this.ultraGridDocumentExporter1.Export(ug_OrderItemsInvoiceItems_interfaceView, nombreYruta, Infragistics.Win.UltraWinGrid.DocumentExport.GridExportFileFormat.PDF);                
                    //exportTo_TXT(ug_OrderItemsInvoiceItems_interfaceView);
                    fileExported = true;
                
            }
            catch (Exception Ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, Ex.InnerException);
            }
            return;
        }

        private void exportTo_TXT(Infragistics.Win.UltraWinGrid.UltraGrid uggridToExport)
        {
            string lineaAGuardar = "";

            try
            {
                foreach (UltraGridCell cell in uggridToExport.Rows[0].Cells)
                {
                    lineaAGuardar += cell.Column.Key + "\t";//cell.Column.Header.Caption                    
                }
                lineaAGuardar += "\n";

                foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in uggridToExport.Rows)
                {
                    for (int i = 0; i < row.Cells.Count; i++)
                    {
                        lineaAGuardar += row.Cells[i].Value.ToString() + "\t";
                    }
                    lineaAGuardar += "\n";
                }
                string tempFileName = System.IO.Path.GetTempFileName();
                System.IO.StreamWriter writer = System.IO.File.CreateText(tempFileName);
                writer.Write(lineaAGuardar);
                writer.Close();

                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.FileName = "wordpad.EXE"; //"notepad.EXE";//
                startInfo.Arguments = Environment.GetEnvironmentVariable("TMP") + "\\" + System.IO.Path.GetFileName(tempFileName).ToString(); //tempFileName;

                if (MessageBox.Show(this, "Do you want to open the file?", "Data Successfully Exported", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show("Error " + ee.Message);
            }
        }

        //--Export to Excel
        public void exportExcel()
        {
            System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
            dialogo.DefaultExt = "xls";
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter Exporter = new Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter();

            

            if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Exporter.Export(ug_OrderItemsInvoiceItems_interfaceView, dialogo.FileName);
                if (MessageBox.Show(this, "Do you want to open the file?", this.Text, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void ug_OrderItemsInvoiceItems_interfaceView_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                e.Row.Cells["cdOrder"].Appearance.BackColor = Color.SkyBlue;
                e.Row.Cells["cdInvoice"].Appearance.BackColor = Color.SkyBlue;
            }
        }        
    }
}
